﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dukou.DTO
{
    /// <summary>
    /// 对象解析器
    /// </summary>
    /// <typeparam name="T">在网络传输的对象</typeparam>
    /// <typeparam name="K">一般对象</typeparam>
    [Serializable]
    public abstract class ObjectParser<T, K> : ObjectParser
        where T : IUniqueIdentifier
        where K : IUniqueIdentifier
    {
        private bool TryGetValue(string key, IDictionary<string, ObjectCache> caches, out ObjectCache result)
        {
            result = null;
            if (caches.TryGetValue(key, out result))
            {
                 return true;
            }

            return false;
        }

        public T Parse(K k, IDictionary<string, ObjectCache> caches, int depth)
        {
            if (k == null || depth < 0)
            {
                return default(T);
            }

            ObjectCache cache = null;
            if (TryGetValue(k.GetIdentity(), caches, out cache))
            {
                if (cache.Depth < depth)
                {
                    cache.Depth = depth;
                }
                return (T)cache.Cache;
            }

            return InternalParse(k, caches, depth);
        }

        public K Parse(T t, IDictionary<string, ObjectCache> caches, int depth)
        {
            if (t == null || depth < 0)
            {
                return default(K);
            }

            ObjectCache cache = null;
            if (TryGetValue(t.GetIdentity(), caches, out cache))
            {
                if (cache.Depth < depth)
                {
                    cache.Depth = depth;
                }
                return (K)cache.Cache;
            }

            return InternalParse(t, caches, depth);
        }

        protected abstract T InternalParse(K k, IDictionary<string, ObjectCache> caches, int depth);

        protected abstract K InternalParse(T t, IDictionary<string, ObjectCache> caches, int depth);
    }
}
